package nina.yiyou.salary.output

import groovy.transform.PackageScope
import nina.yiyou.salary.output.util.CsvLineMaker
import nina.yiyou.salary.output.util.OutCsvWriter

import java.nio.file.Path
import java.util.function.Function


@PackageScope
class EmployeeCsvExporter {

  EmployeeCsvExporter(List<Map> employeeList, List<String> keyList, Map<String, ?> globalResult, Path csvPath) {
    _employeeList = employeeList
    _keyList = keyList
    _globalResult = globalResult
    _csvPath = csvPath
  }

  void export() {
    new OutCsvWriter(_csvPath, _employeeList
        .toSorted(makeSorter())
        .collect { toCsvLine(it) }).write()
  }

  private Comparator makeSorter() {
    Map<String, Integer> depMap = (_globalResult['全局.部门排序'] as String)
        .split(/\|/).toList()
        .withIndex()
        .collectEntries { [it[0], it[1] + 1] }

    // 排序值不能有0，避免排序的时候被过滤掉
    assert depMap.values().every()

    def dep = { Map l -> l['基本.部门'] as String }
    return Comparator
        .comparing({ depMap[dep(it)] ?: Integer.MAX_VALUE } as Function<Map, Integer>)
//        .thenComparing({ dep(it) } as Function)
        .thenComparing({ it['基本.工号'] } as Function)
  }

  private String toCsvLine(Map employeeMap) {
    List lineVal = _keyList.collect { employeeMap.containsKey(it) ? employeeMap[it] : '' }
    return new CsvLineMaker(lineVal).make()
  }

  private final List<Map> _employeeList
  private final List<String> _keyList

  private final Map<String, ?> _globalResult
  private final Path _csvPath
}
